package gw.com.android.utils;

import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;

import com.payegis.caesar.sdk.EnumUploadPolicy;
import com.payegis.caesar.sdk.PayegisDidCallback;
import com.payegis.caesar.sdk.PayegisDidMessage;
import com.payegis.caesar.sdk.PayegisDidSdk;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;

/**
 * @author jett
 * @since 2018-07-17.
 */
public class PayegisUtil {

    private final static String APP_ID = ENV.isUat() ? "5308e20b" : "x97yn05t";
    private final static String APP_KEY = "3daf27ea2fe840ada6af8e1ec0d7b760";
    private final static String SERVER_URL = ENV.isUat() ? "http://192.168.75.240:8080/did" : "https://sjmd.gwghk.com/did";

    public static void initPayEgis(final Context context) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            init(context);
        } else {
            AppMain.getApp().getHandler().post(new Runnable() {
                @Override
                public void run() {
                    init(context);
                }
            });
        }
    }

    /**
     * 初始化，通付盾，需在主线程中调用。。。
     */
    private static void init(Context context) {
        PayegisDidSdk.getInstance().init(context, APP_ID, APP_KEY, SERVER_URL);
        // 设置是否为调试模式
        //PayegisDidSdk.getInstance().setDebugMode(true);
        // 批量上传策略下设置批量的临界值
        //PayegisDidSdk.getInstance().setBatchEventCount(30);
        PayegisDidSdk.getInstance().setUploadPolicy(EnumUploadPolicy.STAT_POLICY_REALTIME);
        trackEvent("start_up");
    }

    public static void trackEvent(final String event) {
        final String sessionId = UUID.randomUUID().toString();
        PayegisDidSdk.getInstance().generateDeviceId(sessionId, new PayegisDidCallback() {
            public void actionSucceed(PayegisDidMessage paramPGSMessage) {
                //Logger.i("initPayEgis", "init success");
                Map<String, String> param = new HashMap<>();
                param.put("action", event);
                param.put("appId", APP_ID);
                param.put("sessionId", sessionId);
                param.put("bu", "HXPMFT");
                param.put("tradePlatform", "GTS2");
                if (!TextUtils.isEmpty(GTConfig.instance().mCurName)) {
                    param.put("accountNo", GTConfig.instance().mCurName);
                }
                PayegisDidSdk.getInstance().trackCustomEvent(event, param);
            }

            @Override
            public void actionFailed(PayegisDidMessage paramPGSMessage) {
                //Logger.i("initPayEgis", "init fail, code: " + paramPGSMessage.getStatus() + ",message:" + paramPGSMessage.getMessage());
            }
        });
    }

}
